//
//  InviteAlert.m
//  VivaModa
//
//  Created by Sergey on 3/3/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "InviteAlert.h"
#import <QuartzCore/QuartzCore.h>


@interface InviteAlert ()
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) UITextField *plainTextField;

- (void)orientationDidChange:(NSNotification *)notification;
- (void) drawRoundedRect:(CGRect) rect inContext:(CGContextRef)
context withRadius:(CGFloat) radius;
@end

static UIColor *fillColor = nil;
static UIColor *borderColor = nil;

@implementation InviteAlert


@synthesize tableView = tableView_;
@synthesize plainTextField = plainTextField_;


/*
 -(BOOL)_needsKeyboard {
 // Private API hack by @0xced (Cedric Luthi) for possible keyboard responder issue: http://twitter.com/0xced/status/29067229352
 return [UIDevice instancesRespondToSelector:@selector(isMultitaskingSupported)];
 }
 */

- (id)initWithTitle:(NSString *)title delegate:(id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitle:(NSString *)otherButtonTitles {
    
	if ((self = [super initWithTitle:title message:@"\n\n\n" delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil])) {
		// FIXME: This is a workaround. By uncomment below, UITextFields in tableview will show characters when typing (possible keyboard reponder issue).
		[self addSubview:self.plainTextField];
        
        
        
		tableView_ = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
		tableView_.delegate = self;
		tableView_.dataSource = self;
		tableView_.scrollEnabled = NO;
		tableView_.opaque = NO;
		tableView_.layer.cornerRadius = 3.0f;
		tableView_.editing = YES;
		tableView_.rowHeight = 28.0f;
		[self addSubview:tableView_];
        
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
		[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
	}
	return self;
}

- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
	[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
	
	[tableView_ setDataSource:nil];
	[tableView_ setDelegate:nil];
	[tableView_ release];
    [super dealloc];
}

#pragma mark layout

- (void)layoutSubviews {
    
    for (UIView *sub in [self subviews])
    {
        if([sub class] == [UIImageView class] && sub.tag == 0)
        {
            // The alert background UIImageView tag is 0,
            // if you are adding your own UIImageView's
            // make sure your tags != 0 or this fix
            // will remove your UIImageView's as well!
            [sub removeFromSuperview];
            break;
        }
    }
    
    
    
	// We assume keyboard is on.
	if ([[UIDevice currentDevice] isGeneratingDeviceOrientationNotifications]) {
		if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
			self.center = CGPointMake(160.0f, (460.0f - 216.0f)/2 + 12.0f);
			self.tableView.frame = CGRectMake(12.0f, 63.0f, 260.0f, 28.0f);
		} else {
			self.center = CGPointMake(240.0f, (300.0f - 162.0f)/2 + 12.0f);
			self.tableView.frame = CGRectMake(12.0f, 35.0f, 260.0f, 28.0f);
		}
	}
    
}

- (void)orientationDidChange:(NSNotification *)notification {
	[self setNeedsLayout];
}

#pragma mark Accessors

- (UITextField *)plainTextField {
    
	if (!plainTextField_) {
		plainTextField_ = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 0.0f, 255.0f, 28.0f)];
		plainTextField_.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
		plainTextField_.clearButtonMode = UITextFieldViewModeWhileEditing;
		plainTextField_.placeholder = @"Введите e-mail друга";
	}
    plainTextField_.autocapitalizationType = UITextAutocapitalizationTypeNone;
	return plainTextField_;
}



#pragma mark UITableViewDataSource & UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	static NSString *AlertPromptCellIdentifier = @"DDAlertPromptCell";
    
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:AlertPromptCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:AlertPromptCellIdentifier] autorelease];
    }
	
    [cell.contentView addSubview:self.plainTextField];
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}











+ (void) setBackgroundColor:(UIColor *) background
            withStrokeColor:(UIColor *) stroke
{
    if(fillColor != nil)
    {
        [fillColor release];
        [borderColor release];
    }
    
    fillColor = [background retain];
    borderColor = [stroke retain];
}

- (id)initWithFrame:(CGRect)frame
{
    if((self = [super initWithFrame:frame]))
    {
        if(fillColor == nil)
        {
            fillColor = [[UIColor blackColor] retain];
            borderColor = [[UIColor colorWithHue:0.625
                                      saturation:0.0 brightness:0.8 alpha:1]
                           retain];
        }
    }
    
    return self;
}


- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextClearRect(context, rect);
    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetLineWidth(context, 0.0);
    CGContextSetAlpha(context, 1);
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, [borderColor CGColor]);
    CGContextSetFillColorWithColor(context, [fillColor CGColor]);
    
    // Draw background
    CGFloat backOffset = 2;
    CGRect backRect = CGRectMake(rect.origin.x + backOffset,
                                 rect.origin.y + backOffset,
                                 rect.size.width - backOffset*2,
                                 rect.size.height - backOffset*2);
    
    [self drawRoundedRect:backRect inContext:context withRadius:8];
    CGContextDrawPath(context, kCGPathFillStroke);
    
    // Clip Context
    CGRect clipRect = CGRectMake(backRect.origin.x + backOffset-1,
                                 backRect.origin.y + backOffset-1,
                                 backRect.size.width - (backOffset-1)*2,
                                 backRect.size.height - (backOffset-1)*2);
    
    [self drawRoundedRect:clipRect inContext:context withRadius:8];
    CGContextClip (context);
    
    //Draw highlight
    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35, 1.0, 1.0, 1.0, 0.06 };
    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace,
                                                        components, locations, num_locations);
    
    CGRect ovalRect = CGRectMake(-130, -115, (rect.size.width*2),
                                 rect.size.width/2);
    
    CGPoint start = CGPointMake(rect.origin.x, rect.origin.y);
    CGPoint end = CGPointMake(rect.origin.x, rect.size.height/5);
    
    CGContextSetAlpha(context, 1.0);
    CGContextAddEllipseInRect(context, ovalRect);
    CGContextClip (context);
    
    CGContextDrawLinearGradient(context, glossGradient, start, end, 0);
    
    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace);
}

- (void) drawRoundedRect:(CGRect) rrect inContext:(CGContextRef) context
              withRadius:(CGFloat) radius
{
    CGContextBeginPath (context);
    
    CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect),
    maxx = CGRectGetMaxX(rrect);
    
    CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect),
    maxy = CGRectGetMaxY(rrect);
    
    CGContextMoveToPoint(context, minx, midy);
    CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
    CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
    CGContextClosePath(context);
}

@end
